package com.example.demo.util;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;
import java.util.Random;

public class FileUtil {

    public static File multipartFile2File(MultipartFile file) throws Exception {
        File imageFolder = new File("E:\\代码\\ASP.net Web程序设计\\web程序设大作业\\后端\\workspace");
        File f = new File(imageFolder, "test.xlsx");
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f;
    }
    public static String getFilePath(MultipartFile file, String folder, String api, String FileType) {
        File imageFolder = new File(folder);
        String s = DateUtil.getTimeStamp();
        s += getRandomString(8) + FileType;
        File f = new File(imageFolder, s);
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            return api + f.getName();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }



}
